package com.scdt.china.shorturl.controller;

import com.scdt.china.shorturl.common.Constants;
import com.scdt.china.shorturl.common.GlobalErrorCode;
import com.scdt.china.shorturl.common.ResultVo;
import com.scdt.china.shorturl.pojo.Url;
import com.scdt.china.shorturl.service.UrlService;
import com.scdt.china.shorturl.utils.JacksonUtil;
import com.scdt.china.shorturl.utils.ShortUrlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @Author: zhouchao
 * @Date: 2021/11/26 13:13
 * @Description:
 */
@Slf4j
@Api
@RestController
@RequestMapping("api/url")
public class UrlController {

    @Autowired
    private UrlService urlService;

    /**
     * 短域名读取接口
     *
     * @param shortUrl 短链接的短码
     * @return url {@link Url} 长链接信息
     */
    @ApiOperation(value = "短域名读取接口", response = Url.class, httpMethod = "GET")
    @GetMapping("{shortUrl}")
    public ResultVo<Url> getShortUrl(@PathVariable @ApiParam(value = "短链接的短码", name = "shortUrl", required = true, example = "12345678") String shortUrl) {
        return urlService.getShortUrl(shortUrl);
    }


    /**
     * 短域名存储接口
     *
     * @param longUrl 长连接地址
     * @return shortUrl {@link String} 短链接信息
     */
    @ApiOperation(value = "短域名存储接口", response = String.class, httpMethod = "POST")
    @PostMapping
    public ResultVo<String> saveShortUrl(@RequestBody @ApiParam(value = "长连接地址", name = "longUrl", required = true, example = "12345678") String longUrl, HttpServletRequest request) {
        if (StringUtils.isEmpty(longUrl)) {
            return ResultVo.failure(GlobalErrorCode.MISS_PARAMETER, null);
        }
        StringBuffer sb = request.getRequestURL();
        String host = sb.delete(sb.length() - request.getRequestURI().length(), sb.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();
        return urlService.saveShortUrl(longUrl, host);
    }

}
